package com.flyduck.modules.system.web;

import com.flyduck.common.annotation.Log;
import com.flyduck.modules.system.domain.SysUser;
import com.flyduck.modules.system.service.SysUserService;
import com.flyduck.common.util.DateUtil;
import com.flyduck.common.vo.AjaxResult;
import com.flyduck.common.vo.PageResult;
import com.flyduck.common.vo.QueryVo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.util.IOUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @program: flyduck-admin
 * @description: 用户管理
 * @author: flyduck
 * @create: 2020-05-06 10:52
 **/
@Controller
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 跳转首页
     *
     * @return
     */
    @Log(value = "跳转到用户管理页面")
    @GetMapping
    @RequiresPermissions("user:list")
    public String index() {
        return "system/user";
    }

    /**
     * 分页数据
     *
     * @return
     */
    @Log("用户分页数据查询")
    @PostMapping("/list")
    @ResponseBody
    @RequiresPermissions("user:list")
    public PageResult findPage(QueryVo queryVo) {
        return sysUserService.findPage(queryVo);
    }

    /**
     * 保存用户
     *
     * @return
     */
    @Log("保存用户")
    @RequiresPermissions("user:add")
    @GetMapping("/save")
    @ResponseBody
    public AjaxResult save(@Valid SysUser sysUser, BindingResult result) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            sysUserService.save(sysUser);
            ajaxResult.setSuccess(true);
            ajaxResult.setMsg("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("保存失败");
        }
        return ajaxResult;
    }

    /**
     * 更新用户
     *
     * @return
     */
    @Log("更新用户")
    @RequiresPermissions("user:edit")
    @GetMapping("/update")
    @ResponseBody
    public AjaxResult update(SysUser sysUser) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            sysUserService.update(sysUser);
            ajaxResult.setSuccess(true);
            ajaxResult.setMsg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("更新失败");
        }
        return ajaxResult;
    }


    /**
     * 启用/禁用用户
     *
     * @return
     */
    @Log("启用/禁用用户")
    @RequiresPermissions(value = {"user:enable", "user:disable"}, logical = Logical.OR)
    @PostMapping("/updateStatus")
    @ResponseBody
    public AjaxResult updateStatus(Long id, Boolean enabled) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            sysUserService.updateStatus(id, enabled);
            ajaxResult.setSuccess(true);
            ajaxResult.setMsg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("更新失败");
        }
        return ajaxResult;
    }

    /**
     * 根据用户id查询用户
     *
     * @return
     */
    @Log("根据用户id查询用户")
    @GetMapping("/getUserById")
    @ResponseBody
    public SysUser getUserById(Long id) {
        return sysUserService.getUserById(id);
    }

    @RequestMapping("downloadExcel")
    @ResponseBody
    public void downloadExcel(HttpServletResponse response) {
        try {
            //1.从数据库查询列表
            QueryVo queryVo = new QueryVo();
            queryVo.setPage(1);
            queryVo.setRows(10);
            PageResult pageResult = sysUserService.findPage(queryVo);
            List<SysUser> sysUserList = (List<SysUser>) pageResult.getRows();
            //2.创建Excel,写到excel中去
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("员工数据");
            //=====创建一行
            HSSFRow row = sheet.createRow(0);
            //=====设置行的每一列数据
            row.createCell(0).setCellValue("编号");
            row.createCell(1).setCellValue("用户名");
            row.createCell(2).setCellValue("昵称");
            row.createCell(3).setCellValue("电话");
            row.createCell(4).setCellValue("邮箱");
            row.createCell(5).setCellValue("创建时间");
            //=====取出每一个用户设置数据
            HSSFRow userRow = null;
            for (int i = 0; i < sysUserList.size(); i++) {
                SysUser sysUser = sysUserList.get(i);
                userRow = sheet.createRow(i + 1);
                //==========编号
                userRow.createCell(0).setCellValue(sysUser.getId());
                //==========用户名
                userRow.createCell(1).setCellValue(sysUser.getUsername());
                //==========昵称
                userRow.createCell(2).setCellValue(sysUser.getNickName());
                //==========电话
                userRow.createCell(3).setCellValue(sysUser.getPhone());
                //==========邮箱
                userRow.createCell(4).setCellValue(sysUser.getEmail());
                //==========创建时间
                String createTime = sysUser.getCreateTime() == null ?
                        "" : DateUtil.dateToStr(sysUser.getCreateTime(), DateUtil.yyyy_MM_dd_HH_mm_ss);
                userRow.createCell(5).setCellValue(createTime);
            }
            //3.相应给游览器
            String fileName = new String("用户数据.xls".getBytes("utf-8"), "iso8859-1");
            response.setHeader("content-Disposition","attachment;filename="+fileName);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 下载模板
     * @param response
     */
    @RequestMapping("downloadExcelTpl")
    @ResponseBody
    public void downloadExcelTpl(HttpServletRequest request, HttpServletResponse response){
        FileInputStream is = null;
        try {
            //1.相应给游览器
            String fileName = new String("UserTpl.xls".getBytes("utf-8"), "iso8859-1");
            response.setHeader("content-Disposition","attachment;filename="+fileName);
            //2.获取路径
            String realPath = request.getSession().getServletContext().getRealPath("static/ExcelTml.xls");
            is = new FileInputStream(realPath);
            IOUtils.copy(is,response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ;
            }
        }
    }

    /**
     * 上传excel(要配置文件上传解析器)
     * @return
     */
    @RequestMapping("uploadExcelFile")
    @ResponseBody
    public AjaxResult uploadExcelFile(MultipartFile excel){
        AjaxResult ajaxResult = new AjaxResult();


        try {
            HSSFWorkbook workbook = new HSSFWorkbook(excel.getInputStream());
            HSSFSheet sheet = workbook.getSheetAt(0);
            //1.获取最大行
            int lastRowNum = sheet.getLastRowNum();
            Row row = null;
            for(int i = 1;i<=lastRowNum;i++){
                row = sheet.getRow(i);
                SysUser sysUser = new SysUser();
                sysUser.setUsername((String) getCellValue(row.getCell(1)));
                sysUser.setNickName((String) getCellValue(row.getCell(2)));
                sysUser.setPhone((String) getCellValue(row.getCell(3)));
                sysUser.setEmail((String) getCellValue(row.getCell(4)));
                String cellValue = (String) getCellValue(row.getCell(5));
                sysUser.setCreateTime(DateUtil.strToDate(cellValue, DateUtil.yyyy_MM_dd_HH_mm_ss));
                sysUser.setPassword("1234");
                sysUserService.save(sysUser);
            }

            ajaxResult.setSuccess(true);
            ajaxResult.setMsg("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("上传失败");
        }

        return ajaxResult;

    }

    private Object getCellValue(Cell cell){
        switch (cell.getCellType()) {
            case STRING:
                return cell.getRichStringCellValue().getString();
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue();
                } else {
                    return cell.getNumericCellValue();
                }
            case BOOLEAN:
                return cell.getBooleanCellValue();
            case FORMULA:
                return cell.getCellFormula();
        }
        return cell;
    }
}
